package learnning.dao;

import java.util.List;

import learnning.entity.City;
import util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

public class CityDao {
	public Long saveCity(String cityName) {
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null;
		Long cityId = null;
		try {
			transaction = session.beginTransaction();
			City city = new City();
			city.setName(cityName);
			cityId = (Long) session.save(city);
			transaction.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return cityId;
	}

	@SuppressWarnings("unchecked")
	public void getListCity() {
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			List<City> cities = session.createQuery("from City").list();
			for (City city : cities) {
				System.out.println(city.getName());
			}
			transaction.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public void updateCity(long cityId, String cityName) {
		Session session = HibernateUtil.getSessionfactory().openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			City city = (City) session.get(City.class, cityId);
			city.setName(cityName);
			transaction.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
